/**
 * Local Image Upload Test
 * 
 * This example demonstrates how to upload a local image file to ComfyUI server
 * and use it with the AI Model Face & Hair Detail Fix template.
 */

import { ComfyUIClient, aiModelFaceHairFixTemplate } from '../src';
import * as path from 'path';

async function testLocalImageUpload() {
  console.log('🚀 Starting Local Image Upload Test');
  
  // Initialize client
  const client = new ComfyUIClient({
    baseUrl: 'http://192.168.0.193:8188'
  });

  try {
    // Connect to ComfyUI server
    console.log('📡 Connecting to ComfyUI server...');
    await client.connect();
    console.log('✅ Connected successfully!');

    // Register the template
    console.log('📝 Registering AI Model Face & Hair Fix template...');
    client.templates.registerFromData(aiModelFaceHairFixTemplate);
    const template = client.templates.getById(aiModelFaceHairFixTemplate.metadata.id);
    
    if (!template) {
      throw new Error('Failed to register template');
    }
    console.log('✅ Template registered!');

    // Example 1: Manual upload then execute
    console.log('\n📤 Method 1: Manual Upload + Execute');
    
    // 模拟本地图片路径 - 您需要替换为实际的本地路径
    const localImagePath = 'C:\\Users\\imeep\\Downloads\\20250808-111737.png';
    
    try {
      // Upload image first
      console.log(`📤 Uploading image from: ${localImagePath}`);
      const uploadedFilename = await client.uploadImageFromPath(localImagePath);
      console.log(`✅ Image uploaded successfully as: ${uploadedFilename}`);

      // Execute template with uploaded image
      console.log('🎨 Executing template with uploaded image...');
      const result1 = await client.executeTemplate(template, {
        input_image: uploadedFilename,
        face_prompt: 'beautiful woman, perfect skin, detailed facial features',
        face_denoise: '0.25'
      }, {
        callbacks: {
          onProgress: (progress) => {
            const percentage = Math.round((progress.progress / progress.max) * 100);
            console.log(`⏳ Progress: ${percentage}% (${progress.progress}/${progress.max}) - Node: ${progress.nodeId}`);
          },
          onExecuting: (nodeId) => {
            console.log(`🔄 Executing node: ${nodeId}`);
          }
        },
        timeout: 120000
      });

      if (result1.success) {
        console.log('🎉 Method 1 completed successfully!');
        console.log(`📊 Execution time: ${result1.executionTime}ms`);
        const imageUrls = client.outputsToUrls(result1.outputs || {});
        console.log('🖼️  Enhanced Image URLs:', imageUrls);
      }

    } catch (uploadError) {
      console.log(`⚠️  Method 1 failed (likely file not found): ${uploadError}`);
      console.log('💡 This is expected if the test image path doesn\'t exist on your system');
    }

    // Example 2: One-step upload and execute
    console.log('\n📤 Method 2: One-Step Upload + Execute');
    
    try {
      const result2 = await client.executeTemplateWithLocalImage(
        template,
        {
          face_prompt: 'stunning model, flawless skin, professional photography',
          face_denoise: '0.3'
        },
        localImagePath,
        {
          callbacks: {
            onProgress: (progress) => {
              const percentage = Math.round((progress.progress / progress.max) * 100);
              console.log(`⏳ Progress: ${percentage}% (${progress.progress}/${progress.max}) - Node: ${progress.nodeId}`);
            }
          },
          timeout: 120000
        }
      );

      if (result2.success) {
        console.log('🎉 Method 2 completed successfully!');
        console.log(`📊 Execution time: ${result2.executionTime}ms`);
        const imageUrls = client.outputsToUrls(result2.outputs || {});
        console.log('🖼️  Enhanced Image URLs:', imageUrls);
      }

    } catch (uploadError) {
      console.log(`⚠️  Method 2 failed (likely file not found): ${uploadError}`);
      console.log('💡 This is expected if the test image path doesn\'t exist on your system');
    }

    // Example 3: Show how to use different local paths
    console.log('\n📋 Example Local Image Paths:');
    console.log('Windows: C:\\Users\\username\\Pictures\\image.jpg');
    console.log('Windows: C:\\Users\\username\\Downloads\\photo.png');
    console.log('macOS: /Users/username/Pictures/image.jpg');
    console.log('Linux: /home/username/Pictures/image.jpg');
    console.log('Relative: ./assets/test-image.jpg');

  } catch (error) {
    console.error('💥 Error:', error);
  } finally {
    // Disconnect
    console.log('\n🔌 Disconnecting...');
    await client.disconnect();
    console.log('👋 Disconnected!');
  }
}

// Usage instructions
function showUsageInstructions() {
  console.log('\n📖 How to Use Local Images with ComfyUI SDK:');
  console.log('');
  console.log('1. 🖼️  Prepare your local image:');
  console.log('   - Supported formats: JPG, PNG, GIF, WebP, BMP, TIFF');
  console.log('   - Example path: "C:\\Users\\imeep\\Downloads\\20250808-111737.png"');
  console.log('');
  console.log('2. 📤 Method 1 - Manual Upload:');
  console.log('   const filename = await client.uploadImageFromPath(localPath);');
  console.log('   const result = await client.executeTemplate(template, { input_image: filename });');
  console.log('');
  console.log('3. 🚀 Method 2 - One-Step (Recommended):');
  console.log('   const result = await client.executeTemplateWithLocalImage(');
  console.log('     template, parameters, localImagePath, options');
  console.log('   );');
  console.log('');
  console.log('4. 🔗 Get Result URLs:');
  console.log('   const imageUrls = client.outputsToUrls(result.outputs);');
  console.log('   // Use these URLs to download or display the enhanced images');
}

// Run the test
async function runTest() {
  showUsageInstructions();
  await testLocalImageUpload();
}

// Execute if run directly
if (require.main === module) {
  runTest();
}

export { testLocalImageUpload, showUsageInstructions };
